

#include "unity.h"
#include "unity_fixture.h"

#include "Debug.h"
#include "BSP_Sleep.h"
#include "log/log2.h"

#include "FreeRTOS.h"
#include "task.h"

#include <phNfcLib_Initialization.h>
#include "Utility.h"
#include <Reader/Reader.h>
#include <Reader/reader_mfdf.h>
#include <Reader/reader_wavelynx.h>
#include <Reader/reader_samav3.h>
#include "phDriver.h"

TEST_GROUP(Desfire3);


TEST_SETUP(Desfire3)
{
	reader.hfFlags = TAG_MASK_MIFARE;
	Reader_NFC_LoadProfile(reader.hfFlags, 0, 0, 0);
}

TEST_TEAR_DOWN(Desfire3)
{
	Reader_NFC_RfOff();
}




static int reader_wavelynx_reset_default_key(void){
	int ret = 0;
	ret = samav3_disable_key_entry(SAM_KID_GOOGLE);
	if(ret){
		LOG2_ERR("samav3_reset_key_entry(%d) fail: %d", SAM_KID_GOOGLE, ret);
		return ret;
	}	
	ret = samav3_disable_key_entry(SAM_KID_APPLE_PRIV);
	if(ret){
		LOG2_ERR("samav3_disable_key_entry(%d) fail: %d", SAM_KID_APPLE_PRIV, ret);
		return ret;
	}
	ret = samav3_disable_key_entry(SAM_KID_APPLE_CRED);
	if(ret){
		LOG2_ERR("samav3_disable_key_entry(%d) fail: %d", SAM_KID_APPLE_CRED, ret);
		return ret;
	}

	return 0;
}

//	int wavelynx_main(void);
int reader_wavelynx_init(void);
int reader_wavelynx_load_keys(void);

// int reader_wavelynx_read(credential_t* cred);
int reader_wavelynx_config_tag(credential_t* cred);
int reader_wavelynx_load_default_keys(void);

int reader_wavelynx_gen_mac(void);

int reader_cfg_load_default_key(void);
void reader_wavelynx_config_init(void);
int reader_wavelynx_config3(SimpleTag_T* tag);

phStatus_t phDriver_TimerStart(phDriver_Timer_Unit_t eTimerUnit, uint32_t dwTimePeriod, pphDriver_TimerCallBck_t pTimerCallBack);

TEST(Desfire3, read_wavelynx)
{
	int ret;
	phStatus_t	status = 0;
	ret = reader_mfdf_init();
	if(ret){
		LOG2_ERR("reader_mfdf_init fail: %d", ret);
		// return ret;
	}

	/* Load DESFire default keys into SAM */
	// reader_wavelynx_load_keys();

	// ret = reader_wavelynx_gen_mac();
	/*----------------------------------*/
	/*SAM AV3 is now prepared and active*/
	/*----------------------------------*/
	credential_t cred;
	while(1){
		Reader_NFC_RfOff();
		// LOG2_INF("timer start");
		// phDriver_TimerStart(PH_DRIVER_TIMER_MILLI_SECS, 20, NULL);
		// LOG2_INF("timer end");		
		BSP_Sleep_Ms(500);
		ret = Reader_NFC_DiscoveryStd3(&cred.tag, PHAC_DISCLOOP_POS_BIT_MASK_A, 5);
		if(!ret){
			
			samav3_activate2();
			// ret = reader_wavelynx_read(&cred);
			
			LOG2_INF("wavelynx start!");
			uint32_t t0 = xTaskGetTickCount();
			ret = reader_read_wavelynx_tag(&reader, &cred);
			log_reset_level();
			LOG2_INF("wavelynx time: %u ms", (uint32_t)(xTaskGetTickCount() - t0));
			LOG2_INF("wavelynx end!");
			if(!ret){
					LOG2_BUF_INF("CRED", cred.credential, cred.clen);
					BSP_Sleep_Ms(500);
			}
			else
			if(ret == 1 || ret == 2){
				 ret = reader_wavelynx_config3(&cred.tag);
			}
			
			samav3_deactivate();
			// ret = reader_wavelynx_gen_mac();
		}
	}
}


